import React, { useState, useEffect, Suspense } from 'react'
import { Layout, Menu, Breadcrumb, Button, Modal, message } from 'antd'
import {
    UserOutlined,
    LaptopOutlined,
    CalculatorOutlined,
    ExclamationCircleOutlined,
    MenuUnfoldOutlined,
    MenuFoldOutlined,
    AppstoreOutlined,
    AccountBookOutlined,
    RedEnvelopeOutlined
} from '@ant-design/icons'
import { Route, Link, Switch } from 'react-router-dom'
import { bindActionCreators } from 'redux'
import { useDispatch } from 'react-redux'
import { actionCreators } from '../../redux/actions'
import './index.less'
import HerderLogo from '../../assets/headerlogo.png'
import { getRightsMenus } from '../../app/rights'
import { MENUS_TITLE } from '../../utils/constant'
import { getItem, removeItem, setItem } from '../../utils/storage'

const { SubMenu } = Menu
const { Header, Content, Sider } = Layout
const { confirm } = Modal

const rootSubmenuIcons = {
    0:< UserOutlined/>,
    1:< LaptopOutlined/>,
    2:< RedEnvelopeOutlined/>,
    3:< AccountBookOutlined/>,
    4:< CalculatorOutlined/>
}
export default function Home (props) {
    // console.log(props);
    const { childrenRoutes } = props
    // console.log(history);
    const dispatch = useDispatch()
    const { logoutAsync } = bindActionCreators(actionCreators, dispatch)
    const [openKeys, setOpenKeys] = useState(getItem(MENUS_TITLE)||[])
    const [collapsed, setCollapsed] = useState(false)
    // 获取菜单列表项
    const [menusList, setMenusList] = useState([])
    // 获取所有一级菜单的title
    const [rootSubmenuKeys, setRootSubmenuKeys] = useState([])
    // 获取所选菜单父子级title
    const [subMenusTitle, setSubMenusTitle] = useState(getItem(MENUS_TITLE)||[])
    // 获取菜单列表的useEffect
    useEffect(async () => {
        // 获取菜单列表
        const { data, meta } = await getRightsMenus()
        if(meta.status !== 200) {
            return message.error('获取菜单列表失败', 1)
        }
        setMenusList(data)
    }, [])
    // 获取一级菜单列表的title
    useEffect(() => {
        const menusSubTitle = menusList.map(item => item.authName)
        setRootSubmenuKeys(menusSubTitle)
    }, [menusList])
    // 退出登录
    function logout() {
        confirm({
          title: '是否确认退出！',
          icon: <ExclamationCircleOutlined />,
          okText:'确认',
          cancelText:'取消',
          onOk() {
            logoutAsync({
                token:null,
                isLogin: false
            })
            removeItem(MENUS_TITLE)
          }
        })
      }
    //   侧边导航收缩相互排斥
      const onOpenChange = keys => {
        const latestOpenKey = keys.find(key => openKeys.indexOf(key) === -1);
        // console.log(latestOpenKey);
        if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
          setOpenKeys(keys)
        } else {
          setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
        }
      }
    //   切换侧边导航大小
    const toggleSiderBar = () => {
        setCollapsed((e) => !e)
      }
    // 点击每一项 item 触发
    const clickMenusItem = (obj) => {
        console.log(obj.keyPath);
        setItem(MENUS_TITLE, obj.keyPath)
        setSubMenusTitle(obj.keyPath)
    }
    return (
        <Layout className="home-container" >
            <Header className="header" >
            <div className="logo">
                <img alt="logo图标" src={HerderLogo} />
                <span className="header-text">后台管理系统</span>
            </div>
            <Button onClick={logout} size="large">退出</Button>
            </Header>
            <Layout>
                <Sider
                    className="site-layout-background"
                    collapsed={collapsed}
                    collapsible
                    trigger={null}
                    width={200}
                >
                    <div className="collapsed-row">
                    {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                        className: 'trigger',
                        onClick: toggleSiderBar
                        })}
                    </div>
                    <Menu
                        defaultSelectedKeys={openKeys}
                        defaultOpenKeys={openKeys}
                        mode="inline"
                        onClick={clickMenusItem}
                        onOpenChange={onOpenChange}
                        openKeys={openKeys}
                        style={{ height: '100%', borderRight: 0 }}
                    >
                        {
                          menusList.map((item, index) => {
                              return (
                                <SubMenu icon={rootSubmenuIcons[index]} key={item.authName} title={item.authName}>
                                    {
                                        item.children.map(obj => {
                                            return (
                                                <Menu.Item icon={<AppstoreOutlined />} key={obj.authName}><Link className="link-text" to={'/' + obj.path} >{obj.authName}</Link></Menu.Item>
                                            )
                                        })
                                    }
                               </SubMenu>
                              )
                          })
                        }
                    </Menu>
                </Sider>
                <Layout style={{ padding: '0 24px 24px' }}>
                    <Breadcrumb style={{ margin: '16px 0' }}>
                    <Breadcrumb.Item>首页</Breadcrumb.Item>
                    <Breadcrumb.Item>{subMenusTitle[1]}</Breadcrumb.Item>
                    <Breadcrumb.Item>{subMenusTitle[0]}</Breadcrumb.Item>
                    </Breadcrumb>
                    <Content
                        className="site-layout-background"
                        style={{
                        padding: 0,
                        margin: 0,
                        minHeight: 280
                    }}
                    >
                        <Suspense fallback={<h1>加载中...</h1>}>
                            <Switch>
                        {
                            childrenRoutes.map(item => {
                                return <Route exact component={item.component} key={item.path} path={item.path} />
                            })
                        }
                            </Switch>
                        </Suspense>
                    </Content>
                </Layout>
            </Layout>
      </Layout>
    )
}